/**
 * 页面初始化通用方法
 */
$(document).ready(function(){
    $.ext.init();
}); 
;(function($){
    $.ext = {
            init:function(){
                $.ext.initTab();
                $.ext.initDialogEvent();
                $.ext.initConfirmEvent();
                $.ext.initAjaxFormSubmit();
                $.ext.templateLoad();
            },
            initTab: function(){
                $('.tab .tab-nav li').each(function(){
                    var e=$(this);
                    var trigger=e.closest('.tab').attr("data-toggle");
                    if (trigger=="hover"){
                        e.mouseover(function(){
                            $showtabs(e);
                        });
                        e.click(function(){
                            return false;
                        });
                    }else{
                        e.click(function(){
                            $showtabs(e);
                            return false;
                        });
                    }
                });
                $showtabs=function(e){
                    var detail=e.children("a").attr("href");
                    e.closest('.tab .tab-nav').find("li").removeClass("active");
                    e.closest('.tab').find(".tab-body .tab-panel").removeClass("active");
                    e.addClass("active");
                    $(detail).addClass("active");
                };
            },
            initPreviewImage: function(){
                $("img[data-component='preview']").each(function(i){
                    var w = $(window).width();
                    var h = $(window).height();
                    $(this).hover(function(e){
                        if(/.png$|.gif$|.jpg$|.bmp$|.jpeg$/.test($(this).attr("data-bimg"))){
                            $("body").append("<div id='preview'><img src='"+$(this).attr('data-bimg')+"' /></div>");
                        }
                        var show_x = $(this).offset().left + $(this).width();
                        var show_y = $(this).offset().top;
                        var scroll_y = $(window).scrollTop();
                        $("#preview").css({
                            position:"absolute",
                            padding:"4px",
                            border:"1px solid #f3f3f3",
                            backgroundColor:"#eeeeee",
                            top:show_y + "px",
                            left:show_x + "px",
                            zIndex:1000
                        });
                        $("#preview > div").css({
                            padding:"5px",
                            backgroundColor:"white",
                            border:"1px solid #cccccc"
                        });
                        if (show_y + 230 > h + scroll_y) {
                            $("#preview").css("bottom", h - show_y - $(this).height() + "px").css("top", "auto");
                        } else {
                            $("#preview").css("top", show_y + "px").css("bottom", "auto");
                        }
                        $("#preview").fadeIn("fast");
                    },function(){
                        $("#preview").remove();
                    });					  
                });
            },
            initDialogEvent:function(){
                //弹窗表单
                $('body').on('click', '.J_showdialog',function(){
                    var self = $(this),
                        dtitle = self.attr('data-title') || '',
                        dtarget = self.attr('data-target'),
                        dwidth = self.attr('data-width') ? parseInt(self.attr('data-width')) :  600,
                        dheight = self.attr('data-height') ? parseInt(self.attr('data-height')) : 450;
                    //iframe   load  
                    var type = 1,content,
                    area = eval("['"+dwidth+"px', '"+dheight+"px']");
                    if(dtarget.indexOf('load') >= 0){
                        content = "<div id=\"innerCont\">Loading...</div>";
                        var url = content = dtarget.split(":")[1];
                        $.getJSON(url,function(html){
                            $("#innerCont").html(html);
                        });
                    }else if(dtarget.indexOf('iframe') >= 0){
                        type = 2;
                        content = dtarget.split(":")[1];
                    }else if(dtarget.substr(0,1) == '#' || dtarget.substr(0,1) == '.'){
                        content = $(dtarget).html();
                    }
                    layer.open({
                        type: type,
                        title: dtitle,
                        shadeClose: true,
                        shade: 0.8,
                        area: area,
                        content: content 
                    }); 
                });
            },
            //初始化确认提示事件
            initConfirmEvent : function(){
                $('body').on('click','.J_confirmurl', function(){
                    var self = $(this),
                        uri = self.attr('act-uri'),
                        msg = self.attr('act-msg') || '您确认该操作吗',
                        callback = self.attr('act-callback');
                    
                    layer.confirm(msg, {
                        btn: ['确定','取消'], //按钮
                        shade: false //不显示遮罩
                    }, function(index){
                        $.getJSON(uri, function(result){
                        	layer.close(index); 
                            if(result.status == 1){
                                $.success(result.msg);
                                setTimeout(function(){
                                    if(callback != undefined){
                                        eval(callback);
                                    }else{
                                        if(result.data && result.data.jumpUrl){
                                            redirct(result.data.jumpUrl);
                                        }else{
                                            window.location.reload();
                                        }
                                    }
                                },500);
                            }else{
                                $.error(result.msg);
                            }
                        });
                        return false;
                    }, function(index){
                    	layer.close(index); 
                    });
                });
            },
            initAjaxFormSubmit:function(){
                $(document).on('click','input.J_ajaxSubmit',function(){
                    var $this = $(this),$form = $this.parentsUntil('form'),
                        callback = $this.attr('onSuccessCallback');
                    //parentsUntil 有bug？
                    while(!$form.is('form')){
                        $form = $form.parent();
                    }
                    //验证
                    if(!$form.doFormValidator()){
                        return;
                    }
                    $this.attr('disabled',true);
                    var loading = layer.load();
                    $form.ajaxSubmit({
                        dataType:"JSON",
                        type: "post",
                        url: $form.attr('action') ,
                        complete: function(){layer.close(loading);},
                        success: function(data){
                        if(data.status!=0){
                             $.success(data.msg);
                             data = data.data;
                             if(callback != undefined){
                                eval(callback +'($this,data)');
                             }
                             if(data && data.jumpUrl){
                            	 setTimeout(function(){redirct(data.jumpUrl);},500);
                             }
                          }else{
                        	 $this.removeAttr('disabled');
                             $.error(data.msg);
                             if(data.data && 'action:doLogin' == data.data){
                        		 setTimeout(function(){$.weiApp.isLogin();},500);
                        	 }
                          }
                        },
                        error: function(XmlHttpRequest, textStatus, errorThrown){
                        	$this.removeAttr('disabled');
                            $.error('error:'+textStatus);
                        }
                     });
                });
            },
			//模板
			templateLoad:function(){
				$('*[templateLoad]').each(function(){
				var $this = $(this),url = $this.attr('templateLoad'),templateId=$this.attr('template-id'),
				templateExtends=$this.attr('template-ext');				
				if(url == '')return;
				if(location.search)url = url + location.search;
				
				var _global = {};//全局拓展只需要加载一次
				var extendsCallback = {};
				if(templateExtends){
					if(templateExtends.indexOf('flowpage') >= 0){
						var _init = false;
						extendsCallback['flowpage'] = function(datas){
							_global['flowpage'] = true;
							var $pageCont = $this.parent().find('.J_page');
							$pageCont.show();
							laypage({
							    cont: $pageCont, 
							    pages: datas.totalPages, 
							    groups: 0,
							    prev: false, 
							    next: '查看更多',
							    skin: 'flow', 
							    jump: function(obj){
							        if(obj.curr === datas.totalPages){
							            this.next = '没有更多了';
							        }
							        if(!_init){_init = true;return;}
							        renderPage({p:obj.curr});
							    }
							});
						}
					}
				}
				//
				renderPage();
				
				function renderPage(params){
					params = params || {};
					if($this.parent().is('form')){
						var query = $this.parent().serializeArray();
						if(query){
							$.each( query, function(i, field){
								params[field.name] = field.value;
							});
						}
					}
					var loading = layer.open({type: 2,content: '努力加载中..'});
					$.getJSON(url,params,function(result){
						layer.close(loading);
						if(result.status == 1){
							if(result.data.totalPages == 0){
								$this.html('暂无数据');
								return;
							}
							if(templateId && templateId != ''){
								var renderData = extendsCallback['flowpage'] ? result.data : result;
								var html = template(templateId, renderData);
								$this.html(html);
							}else{
								var data = result.data;
								$('[bindAttr]',$this).each(function(){
									var self = $(this),bindAttr = self.attr('bindAttr');
									var value;
									//var jsonName = "data['"+bindAttr.replace(".", "']['")+"']";
									try{value = eval('data.'+bindAttr);}catch(e){}
									if(bindAttr == 'bindGroup'){
										
									}else if(bindAttr.indexOf('template:')==0){
										var templateId = bindAttr.replace(/template:/, '');
										var html = template(templateId, data);
										self.html(html);
									}else{
										if(!value)return;
										if(self.is('input') || self.is('textArea')){
											self.val(value);
										}else if(self.is('img')){
											self.attr('src',APP.attachRoot + value);
										}else if(self.is('a')){
											self.attr('href',value);
										}else{
											self.html(value);
										}
									}
								});
							}
							//拓展执行
							for(var index in extendsCallback){
								if(!_global[index]){
									extendsCallback[index](result.data);
								}
							}
						}else{
							
						}
					});
				}
			});
			}
    };
})(jQuery);